package com.cqie.practicaltraining.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.practicaltraining.config.result.R;
import com.cqie.practicaltraining.domain.City;
import com.cqie.practicaltraining.domain.Datas;
import com.cqie.practicaltraining.domain.Enclosures;
import com.cqie.practicaltraining.domain.Pasture;
import com.cqie.practicaltraining.dto.PageResult;
import com.cqie.practicaltraining.dto.PastureDto;
import com.cqie.practicaltraining.dto.PastureSelectDto;
import com.cqie.practicaltraining.service.PastureService;
import com.cqie.practicaltraining.mapper.PastureMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 9977
 * @description 针对表【pasture(牧场)】的数据库操作Service实现
 * @createDate 2024-12-26 10:47:28
 */
@Service
public class PastureServiceImpl extends ServiceImpl<PastureMapper, Pasture> implements PastureService {
    @Autowired
    private EnclosuresServiceImpl enclosuresService;
    @Autowired
    private DatasServiceImpl datasService;
    @Autowired
    private CityServiceImpl cityService;

    @Override
    public R getPastureCondition(PastureSelectDto pastureSelectDto) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(pastureSelectDto.getPastureName() != null, Pasture::getPastureName, pastureSelectDto.getPastureName())
                .eq(pastureSelectDto.getStatus() != null, Pasture::getStatus, pastureSelectDto.getStatus());
        IPage<Pasture> page = new Page<>(pastureSelectDto.getPageNumber(), pastureSelectDto.getPageSize());
        IPage<Pasture> resultPage = page(page, wrapper);
        PageResult<Pasture> result = new PageResult<>(resultPage.getRecords(), pastureSelectDto.getPageNumber(), pastureSelectDto.getPageSize(), resultPage.getTotal());
        if (!result.getRecords().isEmpty())
            return R.Success("查询成功", result);
        return R.Failed("暂无数据");
    }

    @Override
    public R getPastureByPastureId(Long pastureId) {
        if (pastureId == null)
            return R.Failed("参数错误");

        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pasture::getPastureId, pastureId);
        Pasture pasture = getOne(wrapper);

        if (pasture != null) {
            LambdaQueryWrapper<City> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(City::getCityId, pasture.getCityId());
            City city = cityService.getOne(wrapper1);
            Integer parentId = city.getParentId();

            // 使用LinkedList来存储城市名称，便于后续反转
            LinkedList<String> cityNames = new LinkedList<>();
            cityNames.add(city.getName());

            while (parentId != 0) {
                LambdaQueryWrapper<City> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(City::getCityId, parentId);
                City parentCity = cityService.getOne(wrapper2);
                cityNames.addFirst(parentCity.getName());
                parentId = parentCity.getParentId();
            }

            // 将城市名称拼接成字符串
            StringBuilder cityName = new StringBuilder();
            for (String name : cityNames) {
                if (cityName.length() > 0) {
                    cityName.append("/");
                }
                cityName.append(name);
            }

            PastureDto pastureDto = new PastureDto();
            pastureDto.setPastureName(pasture.getPastureName());
            pastureDto.setSize(pasture.getSize());
            pastureDto.setBreedingScale(pasture.getBreedingScale());
            pastureDto.setCityName(cityName.toString());
            pastureDto.setAddress(pasture.getAddress());
            pastureDto.setLongitude(pasture.getLongitude());
            pastureDto.setLatitude(pasture.getLatitude());
            pastureDto.setBreedsLivestock(pasture.getBreedsLivestock());

            return R.Success("查询成功", pastureDto);
        }

        return R.Failed("暂无数据");
    }


    @Override
    public R addPasture(Pasture pasture) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pasture::getPastureName, pasture.getPastureName());
        if (getOne(wrapper) != null)
            return R.Failed("该牧场已存在");
        LambdaQueryWrapper<Datas> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Datas::getDataId, pasture.getDataId());
        if (datasService.getOne(wrapper1) == null)
            return R.Failed("该数据不存在");
        pasture.setBreedsLivestock(datasService.getOne(wrapper1).getDataName());
        pasture.setCreateTime(new Date());
        if (save(pasture))
            return R.Success("添加成功");
        return R.Failed("添加失败");
    }

    @Override
    public R editPasture(Pasture pasture) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pasture::getPastureName, pasture.getPastureName())
                .ne(Pasture::getPastureId, pasture.getPastureId());
        if (getOne(wrapper) != null)
            return R.Failed("该牧场已存在");
        LambdaQueryWrapper<Datas> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Datas::getDataId, pasture.getDataId());
        if (datasService.getOne(wrapper1) == null)
            return R.Failed("该数据字典数据不存在");
        pasture.setBreedsLivestock(datasService.getOne(wrapper1).getDataName());
        pasture.setUpdatedTime(new Date());
        if (updateById(pasture))
            return R.Failed("修改成功");
        return R.Failed("修改失败");
    }

    @Override
    public R changeStatus(Long pastureId) {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pasture::getPastureId, pastureId);
        if (getOne(wrapper) == null)
            return R.Failed("该牧场不存在");
        LambdaQueryWrapper<Enclosures> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Enclosures::getPastureId, pastureId);
        List<Enclosures> enclosuresList = enclosuresService.list(wrapper1);
        List<String> enclosuresNameList = new ArrayList<>();
        int count = 0;
        for (Enclosures enclosures : enclosuresList) {
            if (enclosures.getStatus() == 1) {
                count++;
                enclosuresNameList.add(enclosures.getEnclosuresName());
            }
        }
        if (count > 0)
            return R.Failed("该牧场有" + count + "个" + enclosuresNameList + "的栏位正在使用中，无法修改状态");
        LambdaQueryWrapper<Pasture> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Pasture::getPastureId, pastureId);
        Pasture pasture1 = getOne(wrapper2);
        Long dataId = pasture1.getDataId();
        LambdaQueryWrapper<Datas> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(Datas::getDataId, dataId);
        if (datasService.getOne(wrapper3) != null) {
            if (datasService.getOne(wrapper3).getStatus() == 0)
                return R.Failed("该牧场的牲畜品种已停用，无法修改状态");
        } else {
            return R.Failed("该种牲畜已经下架");
        }
        Pasture pasture = new Pasture();
        if (pasture1.getStatus() == 1)
            pasture.setStatus(0);
        else
            pasture.setStatus(1);
        pasture.setPastureId(pastureId);
        pasture.setUpdatedTime(new Date());
        if (updateById(pasture))
            return R.Success("状态已改变");
        return R.Failed("状态未改变");
    }

    @Override
    public R getAllPastureName() {
        LambdaQueryWrapper<Pasture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pasture::getStatus, 1);
        if (list(wrapper) != null)
            return R.Success("查询成功", list(wrapper));
        return R.Failed("暂无数据");
    }
}




